package com.liulimi.fastapi.core.annotation;


import com.liulimi.fastapi.core.constant.Regexp;
import com.liulimi.fastapi.utils.crypto.MatchUtil;
import io.micrometer.core.instrument.util.StringUtils;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author cuibaoluo
 * @date 2021/1/8
 * @description： 自定义效验参数手机号注解
 */
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = IsMobile.MobileValidator.class)
public @interface IsMobile {

    String message();

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    class MobileValidator implements ConstraintValidator<IsMobile, String> {

        @Override
        public void initialize(IsMobile isMobile) {
        }

        @Override
        public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
            try {
                if (StringUtils.isBlank(s)) {
                    return true;
                } else {
                    String regex = Regexp.MOBILE_REG;
                    return MatchUtil.match(regex, s);
                }
            } catch (Exception e) {
                return false;
            }
        }

    }
}
